<template>
  <div class="p-2">
    <el-card shadow="never" body-class="projectCont">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Refresh" @click="syncSite2" v-hasPermi="['oce:site:syncSite']">同步落地页</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="openTemplate">选择策略</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="openRuleConfiguration">规则配置</el-button>
          </el-col>
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">
              {{ appStore.accountName || '未设置' }}
            </div>
          </div>
        </el-row>
      </template>
      <div class="flex flex-wrap text-[12px] pb-[15px] px-[10px] account">
        <div
          class="flex flex-col mx-[4px] bg-[#f1f1f1] px-[10px] py-[6px] rounded-[4px] item relative"
          v-for="(item, index) in advertiserArray"
          :key="index"
        >
          {{ item.name }}
          <div class="text-[#999]">ID：{{ item.id }}</div>
          <div class="absolute cursor-pointer top--1 right--1" @click="removeAdvertiser(index)">
            <el-icon><CircleClose /></el-icon>
          </div>
        </div>
      </div>
      <div class="flex text-[14px] content">
        <div class="w-[19%] shrink-0 border-solid border-[1px] border-[#f1f1f1] items">
          <div class="flex justify-between items-center px-[15px] py-[15px] titbox">
            <div class="title">新建项目</div>
            <!-- <div class="action cursor-pointer text-[#409eff]">切换</div> -->
          </div>
          <div class="conts">
            <div class="empty" v-if="!addProjectInfo.project">
              <el-empty description="No Data">
                <el-button type="primary" @click="openProjectAdd">新建项目</el-button>

                <el-button type="primary" @click="openProjectList" v-if="advertiserArray.length == 1">已有项目</el-button>
              </el-empty>
            </div>
            <div class="" v-else>
              <div class="p-[10px] h-[270px] overflow-y-scroll base">
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">项目名称：</div>
                  <div class="val">{{ addProjectInfo.project.name }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">项目预算：</div>
                  <div class="val">{{ addProjectInfo.project.deliverySetting.budget }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items" v-if="addProjectInfo.project.deliverySetting.cpaBid">
                  <div class="label">项目出价：</div>
                  <div class="val">{{ addProjectInfo.project.deliverySetting.cpaBid }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">项目深度出价：</div>
                  <div class="val">无</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">推广目的：</div>
                  <div class="val">{{ addProjectInfo.project.landingType === 'MICRO_GAME' ? '小程序' : '-' }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">营销场景：</div>
                  <div class="val">短视频/图片</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">优化目标：</div>
                  <div class="val">
                    {{
                      addProjectInfo.project.optimizeGoal.externalAction === 'TYPE_PAY'
                        ? '付费'
                        : addProjectInfo.project.optimizeGoal.externalAction === 'TYPE_GAME_ADDICTION'
                          ? '关键行为'
                          : addProjectInfo.project.optimizeGoal.externalAction === 'TYPE_ACTIVE'
                            ? '激活'
                            : ''
                    }}
                  </div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items" v-if="addProjectInfo?.deliverySetting?.roiGoal">
                  <div class="label">ROI系数：</div>
                  <div class="val">
                    {{ addProjectInfo?.deliverySetting?.roiGoal }}
                  </div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">投放模式：</div>
                  <div class="val">{{ addProjectInfo.project.deliveryMode === 'PROCEDURAL' ? '自动投放(UBMax)' : '手动投放' }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">投放类型：</div>
                  <div class="val">常规投放</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">投放内容：</div>
                  <div class="val">
                    {{
                      addProjectInfo.project.microPromotionType === 'WECHAT_APP'
                        ? '微信小程序'
                        : addProjectInfo.project.microPromotionType === 'BYTE_APP'
                          ? '字节小程序'
                          : '抖音号'
                    }}
                  </div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">竞价策略：</div>
                  <div class="val">
                    {{ addProjectInfo.project.deliverySetting.bidType === 'CUSTOM' ? '稳定成本' : 'NO_BID' }}
                  </div>
                </div>
              </div>
              <div class="flex items-center justify-center full">
                <el-button type="primary" @click="openProjectAdd">修改</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="w-[15%] shrink-0 border-solid border-[1px] border-[#f1f1f1] items">
          <div class="flex justify-between items-center px-[15px] py-[15px] titbox">
            <div class="title">广告信息</div>
          </div>
          <div class="conts">
            <div class="empty" v-if="!addProjectInfo.promotion">
              <el-empty description="No Data">
                <el-button type="primary" @click="handleAddAbs" v-if="addProjectInfo?.project">新建广告</el-button>
              </el-empty>
            </div>
            <!-- v-if="addProjectInfo.project" -->
            <div class="" v-else>
              <div class="p-[10px] h-[270px] overflow-y-scroll base">
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">广告名称：</div>
                  <div class="val">{{ addProjectInfo.promotion.name }}</div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">产品名称：</div>
                  <div class="val">
                    {{
                      addProjectInfo?.project?.relatedProduct?.productName
                        ? addProjectInfo?.project?.relatedProduct?.productName
                        : addProjectInfo.promotion.promotionMaterials.productInfo.titles[0]
                    }}
                  </div>
                </div>
                <div class="flex items-center text-[12px] py-[4px] items">
                  <div class="label">来源：</div>
                  <div class="val">{{ addProjectInfo.promotion.source }}</div>
                </div>
              </div>
              <div class="flex items-center justify-center full">
                <el-button type="primary" @click="handleAddAbs">修改</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="w-[32%] shrink-0 border-solid border-[1px] border-[#f1f1f1] items">
          <div class="flex justify-between items-center px-[15px] py-[15px] titbox">
            <div class="title">创意素材</div>
            <div class="action cursor-pointer text-[#409eff]" @click="delAllMaterialList" v-if="addProjectInfo.groupQos?.length > 0">清空</div>
          </div>
          <div class="conts">
            <div class="material-list" v-if="addProjectInfo.groupQos?.length > 0">
              <div class="h-[270px] overflow-y-scroll">
                <div class="flex items-center mb-[10px] material-item" v-for="(item, index) in addProjectInfo.groupQos" :key="index">
                  <div class="flex items-center img-box" v-for="(itm, idx) in item.videoMaterialList" :key="idx">
                    <img :src="itm.posterUrl" alt="" />
                  </div>
                </div>
              </div>
              <div class="flex items-center justify-center full">
                <el-button type="primary" @click="handleAddMaterial">修改</el-button>
              </div>
            </div>
            <div class="empty" v-else>
              <el-empty description="No Data">
                <el-button type="primary" @click="handleAddMaterial">新增</el-button>
              </el-empty>
            </div>
          </div>
        </div>
        <div class="w-[19%] shrink-0 border-solid border-[1px] border-[#f1f1f1] items">
          <div class="flex justify-between items-center px-[15px] py-[15px] titbox">
            <div class="title">标题包</div>
            <div class="action cursor-pointer text-[#409eff]" @click="addProjectInfo.titleWrap = []" v-if="addProjectInfo.titleWrap?.length > 0">
              清空
            </div>
          </div>
          <div class="conts">
            <div class="header-pack" v-if="addProjectInfo.titleWrap?.length">
              <div class="h-[270px] overflow-y-scroll">
                <div class="flex items-center px-[15px] my-[5px] header-pack-box" v-for="(item, index) in addProjectInfo.titleWrap" :key="index">
                  <div class="header-pack-name">{{ item.name }}</div>
                </div>
              </div>
              <div class="flex items-center justify-center full">
                <el-button type="primary" @click="handleAddHeaderPack">修改</el-button>
              </div>
            </div>
            <div class="empty" v-else>
              <el-empty description="No Data">
                <el-button type="primary" @click="handleAddHeaderPack">新增</el-button>
              </el-empty>
            </div>
          </div>
        </div>

        <div class="w-[15%] shrink-0 border-solid border-[1px] border-[#f1f1f1] items">
          <div class="flex justify-between items-center px-[15px] py-[15px] titbox">
            <div class="title">落地页</div>
            <div
              class="action cursor-pointer text-[#409eff]"
              @click="addProjectInfo.externalUrlMaterialList = []"
              v-if="addProjectInfo.externalUrlMaterialList?.length > 0"
            >
              清空
            </div>
          </div>
          <div class="conts">
            <div class="landing-page" v-if="addProjectInfo.externalUrlMaterialList?.length > 0">
              <div class="h-[270px] overflow-y-scroll">
                <div class="px-[15px] my-[5px] landing-page-box" v-for="(item, index) in addProjectInfo.externalUrlMaterialList" :key="index">
                  <div class="landing-page-name">{{ islandingMethods ? item.appName : item.name }}</div>
                  <div class="landing-page-url" style="" v-if="isUnifiedHand">链接：{{ item.url }}</div>
                </div>
              </div>
              <div class="flex items-center justify-center full">
                <el-button type="primary" @click="handleDrawerLandingPage">修改</el-button>
              </div>
            </div>
            <div class="empty" v-else>
              <el-empty description="No Data">
                <el-button type="primary" @click="handleDrawerLandingPagePack">编辑</el-button>
              </el-empty>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="flex items-center justify-center">
          <el-button type="primary" plain @click="isPolicyGroup = true">保存策略</el-button>
          <el-button type="primary" @click="handleCreate">创建</el-button>
          <el-button type="primary" @click="handlePreview" :disabled="!isPreview">生成预览</el-button>
        </span>
      </template>
    </el-card>
    <el-dialog title="保存策略组" v-model="isPolicyGroup" width="500px" @close="isPolicyGroup = false">
      <el-form ref="policyGroupRef" :model="policyGroup" label-width="100px" class="demo-ruleForm">
        <el-form-item label="策略组名称" :rules="[{ required: true, message: '请输入策略组名称', trigger: 'blur' }]" prop="policyGroupName">
          <el-input v-model="policyGroup.policyGroupName" placeholder="请输入策略组名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="policyGroupRemark" placeholder="请输入备注" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isPolicyGroup = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <SelectPolicy
      ref="selectPolicyRef"
      :isSelectPolicy="isSelectPolicy"
      @update:isSelectPolicy="handleIsSelectPolicy"
      @selectedRows="handleSelectedRows"
    />
    <RuleConfiguration
      ref="openRuleConfigurationRef"
      :isRuleConfiguration="isRuleConfiguration"
      @update:isRuleConfiguration="handleIsRuleConfiguration"
      @ruleSettingData="handleRuleSettingData"
      :ruleSettingMap="ruleSettingMap"
      :isStrategy="selectPolicyList?.id != '' || selectPolicyList?.id != null"
      :projectId="addProjectInfo.projectId"
    />

    <AddProject
      ref="addProjectRef"
      v-if="addShow"
      :userList="advertiserArray"
      @get-value="getProjectInfo"
      @updateInfo="updateUser"
      :project="addProjectInfo.project"
    />
    <CreateAds
      v-if="showAd && advertiserArray.length > 0"
      ref="createAdsRef"
      :drawerAbs="drawerAbs"
      :advertiserId="advertiserArray"
      :microPromotionType="addProjectInfo?.project?.microPromotionType"
      :dramaName="addProjectInfo?.project?.relatedProduct?.productName"
      @update:drawerAbs="handleDrawerAbs"
      @close="handleClose"
      @selectedRows="getPromotion"
      @urls="getUrls"
      @anchorMaterialListData="getAnchorMaterialList"
      :anchorMaterialList="addProjectInfo.anchorMaterialList"
      :promotionData="addProjectInfo.promotion"
      :urlsData="addProjectInfo.urls"
      @strategyUrls="getStrategyUrls"
    />
    <!-- v-if="addProjectInfo.project" -->
    <Material
      v-if="advertiserArray.length > 0"
      :drawerMaterial="drawerMaterial"
      @update:drawerMaterial="handleDrawerMaterial"
      @close="handleClose"
      @selectedRows="getMaterialSelectedRows"
      :userList="advertiserArray"
      :groupQos="addProjectInfo.groupQos"
      @selectAccounts="getSelectAccounts"
      :mySelectAccounts="addProjectInfo.selectAccounts"
      @materialType="getMaterialType"
      :myMaterialType="myMaterialType"
    />
    <HeaderPack
      v-if="advertiserArray.length > 0"
      :drawerHeaderPack="drawerHeaderPack"
      :headerPackList="addProjectInfo.titleWrap"
      :accountList="advertiserArray"
      :titleWay="addProjectInfo.titleWay"
      @update:drawerHeaderPack="handleDrawerHeaderPack"
      @close="handleClose"
      @selectedRows="getHeaderPackSelectedRows"
    />
    <LandingPage
      v-if="advertiserArray.length > 0"
      :drawerLandingPage="drawerLandingPage"
      :accountList="advertiserArray"
      :type="addProjectInfo?.project?.microPromotionType"
      @update:drawerLandingPage="handleDrawerLandingPage"
      @close="handleClose"
      @selectedRows="getLandingPageSelectedRows"
      :userList="advertiserArray"
      @isUnifiedHand="handleIsUnifiedHand"
      @islandingMethods="handleIslandingMethods"
      :siteWay="addProjectInfo.siteWay"
      :drawerLandingPageList="addProjectInfo.externalUrlMaterialList"
      :productName="addProjectInfo?.project?.relatedProduct?.productName"
    />

    <ProjectList v-if="advertiserArray.length > 0" v-model="isShowProjectList" @confirm="onProjectListConfirm" :advertiserArray="advertiserArray" />
    <AdvertiserPreview
      v-if="showAdvPreview && advertiserArray.length > 0"
      :addProjectInfo="addProjectInfo"
      :advertiserArray="advertiserArray"
      :showAdvPreview="showAdvPreview"
      :tableData="tableData"
      :paramsData="paramsData"
    />
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app';
// import TimeSelect from './components/timeSelect.vue';
import ProjectList from './components/projectList.vue';
import AdvertiserPreview from './components/advertiserPreview.vue';
import { queryToolsMicroAppNew, getAllWechatApplet } from '@/api/com';
import { createProjectPromotion, getProjectPromotionTemplate, createProjectPromotionPreview, getProductDetail, getTemplateTask } from '@/api/project';
import { productUrlList } from '@/api/advertising/landingPage';
import { CreateProjectV3Request, Request } from '@/api/project/types';
import { ElMessage, ElMessageBox } from 'element-plus';
import { debounce, union } from 'lodash';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();

const addProjectRef = ref();

const addShow = ref(false);
const showAd = ref(false);
const policyGroupRef = ref();
const createAdsRef = ref();
const selectPolicyList = ref(); // 回显策略组
const adShow = ref(false);
const isSelectPolicy = ref(false);
const ruleSettingMap = ref();
const isRuleConfiguration = ref(false);
const drawerAbs = ref(false);
const drawerMaterial = ref(false);
const drawerHeaderPack = ref(false);
const drawerLandingPage = ref(false);
const isUnifiedHand = ref(false);
const islandingMethods = ref(false);
const promotion = ref();
const urls = ref();
// const headerPackList = ref();
// const drawerLandingPageList = ref();
// 策略组名称
const isPolicyGroup = ref(false);
// const policyGroupName = ref('');
const policyGroupRemark = ref('');
const dramaRef = ref();
const policyGroup = reactive({
  policyGroupName: ''
});
const subLoading = ref(false);
const urlsTemp = ref();
const selectAccounts = ref([]);
const ids = ref(route.query.ids as string);
const advertiserArray = ref([]);
const tableData = ref([]); //预览数据
const paramsData = ref();
const showAdvPreview = ref(false);
const productData = ref();
const strategyUrlList = ref([]); //策略组需要保存格式url
const myMaterialType = ref('1');
const isShowProjectList = ref(false);
// 计算属性来解析 ids
const parseIds = () => {
  if (ids.value) {
    advertiserArray.value = JSON.parse(decodeURIComponent(ids.value));
  } else {
    advertiserArray.value = [];
  }
};
// 初始解析
parseIds();

// 监听 ids 的变化
watch(
  () => route.query.ids,
  (newIds) => {
    ids.value = newIds as string;
    parseIds();
    // initInfo();
    console.log('newIds', newIds);
  },
  { deep: true }
);
// 监听 广告任务中心ids 的变化
watch(
  () => route.query.taskId,
  async (taskId) => {
    console.log('58585858', taskId);
    if (!taskId) {
      return;
    }
    if (taskId) {
      await getTemplateTask(taskId).then((res) => {
        console.log(res, 'res');
        let selectIds = [
          {
            id: res.data.advertiserId,
            name: res.data.advertiserName
          }
        ];
        ids.value = encodeURIComponent(JSON.stringify(selectIds)) as string;
        if (ids.value) {
          advertiserArray.value = JSON.parse(decodeURIComponent(ids.value));
        } else {
          advertiserArray.value = [];
        }
        handleSelectedRows(res.data);
      });
    }
  },
  {
    immediate: true
  }
);
// 获取productName
const handleGetProductDetail = async (productId, productPlatformId) => {
  await getProductDetail({
    advertiserId: advertiserArray.value.map((item) => item.id)[0],
    accountId: appStore.accountId,
    productIds: [productId],
    platformId: productPlatformId
  }).then((res) => {
    if (res.code === 200) {
      productData.value = res.data;
    }
  });
};
// 是否显示生成预览按钮
const isPreview = computed(() => {
  return (
    addProjectInfo.value.project &&
    addProjectInfo.value.promotion &&
    addProjectInfo.value.groupQos?.length > 0 &&
    addProjectInfo.value.titleWrap?.length > 0 &&
    addProjectInfo.value.externalUrlMaterialList?.length > 0
  );
});

const defaultProjectInfo = {
  accountId: appStore.accountId,
  advertiserIds: advertiserArray.value.map((item) => item.id),
  miniProgramInfo: undefined,
  groupQos: undefined,
  materialType: undefined,
  projectNum: 1,
  projectAdRule: 1,
  project: undefined,
  promotion: undefined,
  urls: undefined,
  titleWay: '1',
  siteWay: '1',
  wx: undefined,
  promotionMaterials: undefined,
  externalUrlMaterialList: undefined,
  microAppInstanceList: undefined
};

const addProjectInfo = ref<Request>({ ...defaultProjectInfo });

// const initInfo = () => {
//   addProjectInfo.value = addProjectInfo; // 重新初始化
// };
const getSelectAccounts = (val) => {
  selectAccounts.value = val;
};
// 删除账户
const removeAdvertiser = (index) => {
  if (advertiserArray.value.length === 1) {
    ElMessage.warning('至少保留一个账户');
    return;
  }
  advertiserArray.value.splice(index, 1);
  addProjectInfo.value.advertiserIds = advertiserArray.value.map((item) => {
    return item.id;
  });
  //用于把链接数据也删掉（完全删掉传值），目前没说要这样，暂时隐藏，如果需要就打开注释
  // router.replace({ query: { ids: encodeURIComponent(JSON.stringify(advertiserArray.value)) as string } });
};
/**
 * 打开新建项目
 */
const openProjectAdd = () => {
  addShow.value = true;
  setTimeout(() => {
    addProjectRef.value?.show();
  }, 20);
};
const handleGetProductUrlList = async (productName: any) => {
  if (!productName) return;
  let params = {
    pageNum: 1,
    pageSize: 10,
    name: productName
  };
  const res = await productUrlList(params);
  if (res.code === 200) {
    if (res.rows?.length > 0) {
      addProjectInfo.value.externalUrlMaterialList[0].url = res.rows[0]?.url;
    }
  }
};
//
const onProjectListConfirm = async (val) => {
  await handleGetProductDetail(val.relatedProduct.productId, val.relatedProduct.productPlatformId);
  let newExistingProject = {
    landingType: val.landingType ? val.landingType : 'MICRO_GAME',
    adType: val.adType ? val.adType : 'VIDEO',
    deliveryType: val.deliveryType ? val.deliveryType : 'NORMAL',
    deliveryMode: val.deliveryMode ? val.deliveryMode : 'PROCEDURAL',
    marketingGoal: val.marketingGoal ? val.marketingGoal : 'VIDEO_AND_IMAGE',
    isRelatedgoods: val.isRelatedgoods ? val.isRelatedgoods : 'NO_MAP',
    projectProductWay: val.projectProductWay ? val.projectProductWay : 1,
    microPromotionType: val.microPromotionType ? val.microPromotionType : 'WECHAT_APP',
    microAppInstanceId: val.microAppInstanceId ? val.microAppInstanceId : null,
    relatedProduct: {
      productSetting: val.relatedProduct.productSetting ? val.relatedProduct.productSetting : 'SINGLE',
      productPlatformId: val.relatedProduct.productPlatformId ? val.relatedProduct.productPlatformId : null,
      productId: val.relatedProduct.productId ? val.relatedProduct.productId : null,
      productName: productData.value?.name ? productData.value?.name : null //需要单独处理
    },
    deliveryRange: {
      inventoryCatalog: val.deliveryRange.inventoryCatalog ? val.deliveryRange.inventoryCatalog : 'UNIVERSAL_SMART'
    },
    optimizeGoal: {
      externalAction: val.optimizeGoal.externalAction ? val.optimizeGoal.externalAction : null,
      deepExternalAction: val.optimizeGoal.deepExternalAction ? val.optimizeGoal.deepExternalAction : null,
      assetIds: val.optimizeGoal.assetIds ? val.optimizeGoal.assetIds : null
    },
    deliverySetting: {
      scheduleType: val.deliverySetting.scheduleType ? val.deliverySetting.scheduleType : 'FROM_NOW',
      // startTime: val.deliverySetting.startTime ? val.deliverySetting.startTime : null,
      // endTime: val.deliverySetting.endTime ? val.deliverySetting.endTime : null,
      // scheduleTime: val.deliverySetting.scheduleTime ? val.deliverySetting.scheduleTime : undefined,
      scheduleTimeType: val.deliverySetting.scheduleTimeType ? val.deliverySetting.scheduleTimeType : 0,
      bidType: val.deliverySetting.bidType ? val.deliverySetting.bidType : 'CUSTOM',
      pricing: val.deliverySetting.pricing ? val.deliverySetting.pricing : 'OCPM',
      cpaBid: val.deliverySetting.cpaBid ? val.deliverySetting.cpaBid : null,
      budget: val.deliverySetting.budget ? val.deliverySetting.budget : null,
      budgetMode: val.deliverySetting.budgetMode ? val.deliverySetting.budgetMode : 'DAY',
      deepBidType: val.deliverySetting.deepBidType ? val.deliverySetting.deepBidType : null, // ROI_COEFFICIENT 抖音号不需要
      roiGoal: val.deliverySetting.roiGoal ? val.deliverySetting.roiGoal : null
    },
    userInfo: val.userInfo ? val.userInfo : null,
    audience: {
      platform: val.audience.platform ? val.audience.platform : [],
      hideIfConverted: val.audience.hideIfConverted ? val.audience.hideIfConverted : 'PROMOTION',
      gender: val.audience.gender ? val.audience.gender : 'NONE',
      age: val.audience.age ? val.audience.age : [],
      district: val.audience.district ? val.audience.district : 'NONE',
      city: val.audience.city ? val.audience.city : [],
      locationType: val.audience.locationType ? val.audience.locationType : 'CURRENT'
    },
    name: val.name ? val.name : '<日期>-<花名>-<剧名>-<编号>',
    operation: val.operation ? val.operation : 'ENABLE'
  };
  addProjectInfo.value.projectId = val.projectId; //项目id
  addProjectInfo.value.project = {
    ...newExistingProject,
    ...addProjectInfo.value.project
  };
  await getMircoAppList(val);
};
const getMircoAppList = async (val) => {
  // loading.value = true;
  let params = {
    pageNum: 1,
    pageSize: 100,
    advertiserId: advertiserArray.value[0].id,
    accountId: appStore.accountId
  };
  let productListTemp = [];
  if (addProjectInfo?.value.project?.microPromotionType !== 'AWEME') {
    if (addProjectInfo?.value.project?.microPromotionType === 'WECHAT_APP') {
      const res = await getAllWechatApplet(params);
      productListTemp = res.data;
    } else {
      const res = await queryToolsMicroAppNew(params);
      productListTemp = res.data;
    }
    addProjectInfo.value.microAppInstanceList = productListTemp.filter((itm) => {
      if (itm.instanceId == val.microAppInstanceId) {
        return {
          advertiserId: itm.advertiserId,
          advertiserName: itm.name,
          microAppInstanceId: itm.instanceId,
          microAppName: advertiserArray.value[0].name,
          assetId: itm.assetId
        };
      }
    });
    urlsTemp.value = productListTemp.filter((itm) => itm.instanceId == val.microAppInstanceId);
    // productListTemp.forEach((itm) => {
    //   if (itm.instanceId == form.value?.microAppInstanceId) {
    //     form.value.userInfo.push({
    //       name: form.value.name,
    //       id: itm.advertiserId,
    //       appName: itm.name,
    //       appId: itm.instanceId,
    //       instanceId: itm.instanceId
    //     });
    //   }
    // });
    console.log(addProjectInfo.value, 'productListTemp***');
  }
};
/**
 * 获取项目信息
 */
const getProjectInfo = async (val) => {
  addProjectInfo.value.project = {
    accountId: appStore.accountId,
    // advertiserId: advertiserArray ? advertiserArray.value[0] : null,
    ...val
  };
  addProjectInfo.value.microAppInstanceList = val.userInfo.map((item) => {
    return {
      advertiserId: item.id,
      advertiserName: item.name,
      microAppInstanceId: item.instanceId,
      microAppName: item.appName,
      assetId: item.assetId
    };
  });

  if (addProjectInfo?.value.project?.microPromotionType === 'AWEME') {
    await handleGetProductUrlList(val.relatedProduct?.productName);
  }
  if (addProjectInfo?.value.promotion) {
    addProjectInfo.value.promotion.promotionMaterials.productInfo.titles[0] = val.relatedProduct?.productName;
  }
};
const getMaterialType = (val) => {
  myMaterialType.value = val;
};
const updateUser = (val) => {
  advertiserArray.value = val;
};
const handleSelectedRows = (val) => {
  selectPolicyList.value = val;
  let projectJson = val ? JSON.parse(val.projectJson) : val;

  addProjectInfo.value = {
    ...addProjectInfo.value,
    ...projectJson
  };
  if (val.taskId) {
    addProjectInfo.value.project.name = '<日期>-<花名>-<剧名>-<编号>';
    addProjectInfo.value.promotion.name = '<日期>-<花名>-<剧名>-<编号>';
  }
  //advertiserIds处理
  addProjectInfo.value.titleWay = projectJson.titleWay || '1';
  addProjectInfo.value.advertiserIds = advertiserArray.value.map((item) => {
    return item.id;
  });

  //选择策略的投放内容类型 projectJson.project.microPromotionType
  if (addProjectInfo.value.project?.userInfo) {
    //选择策略后，用户信息中的小程序继承字节中的
    // if (projectJson.project.microPromotionType === 'WECHAT_APP') {
    //   addProjectInfo.value.project.userInfo = advertiserArray.value;
    // } else {
    //   advertiserArray.value.map((item, index) => {
    //     // userinfo里面传的appid都是一样的，取的0条
    //     item.appId = addProjectInfo.value.project.userInfo[0].appId;
    //     item.appName = addProjectInfo.value.project.userInfo[0].appName;
    //     item.instanceId = addProjectInfo.value.project.userInfo[0].instanceId;
    //     item.assetId = addProjectInfo.value.project.userInfo[0].assetId;
    //   });
    //   addProjectInfo.value.project.userInfo = advertiserArray.value;
    // }
    //选择策略后，用户信息中的小程序信息全部重新选
    addProjectInfo.value.project.userInfo = advertiserArray.value;

    if (addProjectInfo.value.project.microPromotionType !== 'AWEME') {
      // 清空微信小程序、字节小程序优化目标
      addProjectInfo.value.project.optimizeGoal.externalAction = null;
      addProjectInfo.value.project.optimizeGoal.deepExternalAction = null;
      //清空microAppInstanceList中的小程序信息
      addProjectInfo.value.microAppInstanceList.map((item) => {
        item.assetId = null;
        item.microAppInstanceId = null;
        item.microAppName = null;
      });
    }
  }
  // if (addProjectInfo.value.project.userInfo) {
  //   addProjectInfo.value.project.userInfo[0].id = advertiserArray.value[0].id;
  //   addProjectInfo.value.project.userInfo[0].name = advertiserArray.value[0].name;
  // }
  if (addProjectInfo.value.promotion) {
    addProjectInfo.value.promotion.advertiserId = advertiserArray.value[0].id;
    // addProjectInfo.value.promotion.urls[0].advertiserId = advertiserArray.value[0].id;
  }
  if (addProjectInfo.value?.urls?.length > 0) {
    const result = JSON.parse(JSON.stringify(addProjectInfo.value.urls));
    // 处理arr1比arr2长的情况
    if (advertiserArray.value.length > result.length) {
      // 添加缺少的元素（只包含advertiserId）
      for (let i = result.length; i < advertiserArray.value.length; i++) {
        result.push({ advertiserId: advertiserArray.value[i].id });
      }
    }
    // 赋值advertiserId
    for (let i = 0; i < advertiserArray.value.length; i++) {
      if (result[i]) {
        result[i].advertiserId = advertiserArray.value[i].id;
      }
    }
    addProjectInfo.value.urls = result;
  }
  if (addProjectInfo.value?.promotion?.urls?.length > 0) {
    const result = JSON.parse(JSON.stringify(addProjectInfo.value.promotion.urls));
    // 处理arr1比arr2长的情况
    if (advertiserArray.value.length > result.length) {
      // 添加缺少的元素（只包含advertiserId）
      for (let i = result.length; i < advertiserArray.value.length; i++) {
        result.push({ advertiserId: advertiserArray.value[i].id });
      }
    }
    // 赋值advertiserId
    for (let i = 0; i < advertiserArray.value.length; i++) {
      if (result[i]) {
        result[i].advertiserId = advertiserArray.value[i].id;
      }
    }
    addProjectInfo.value.promotion.urls = result;
  }

  // if (addProjectInfo.value.urls) {
  // addProjectInfo.value.urls[0].advertiserId = advertiserArray.value[0].id;
  // }
  // addProjectInfo.value.externalUrlMaterialList[0].advertiserId = advertiserArray.value[0].id;
  addProjectInfo.value.titleWrap.map((item) => {
    item.advertiserId = advertiserArray.value[0].id;
  });
  addProjectInfo.value.groupQos.map((item) => {
    item.advertiserId = advertiserArray.value[0].id;
  });
  addProjectInfo.value.anchorMaterialList?.map((item) => {
    item.advertiserId = advertiserArray.value[0].id;
  });
  addProjectInfo.value.externalUrlMaterialList.map((item) => {
    // if (projectJson.project.microPromotionType === 'WECHAT_APP') {
    //   item.instanceId = null;
    //   item.url = null;
    //   item.appId = null;
    //   item.appName = null;
    // } else {
    //   item.advertiserId = advertiserArray.value[0].id;
    //   item.id = advertiserArray.value[0].id;
    // }
    //落地页全部重选
    item.instanceId = null;
    // item.url = null;
    item.appId = null;
    item.appName = null;
  });
  //预览信息重置
  showAdvPreview.value = false;

  console.log(addProjectInfo.value, '回显');
};
const openTemplate = () => {
  isSelectPolicy.value = true;
};
const handleRuleSettingData = (val) => {
  // Object.assign(addProjectInfo.value, val); // 规则字段
  console.log('addProjectInfo', addProjectInfo.value);
  addProjectInfo.value.projectNum = Number(val.projectNum);
  addProjectInfo.value.projectAdRule = val.projectAdRule;
  addProjectInfo.value.promotionNum = Number(val.promotionNum);
};
const openRuleConfiguration = () => {
  isRuleConfiguration.value = true;
  ruleSettingMap.value = {
    projectNum: addProjectInfo.value.projectNum,
    projectAdRule: String(addProjectInfo.value.projectAdRule),
    promotionNum: String(addProjectInfo.value.promotionNum),
    isCreateType: addProjectInfo.value.project ? true : false
  };
};
const handleIsSelectPolicy = (val: boolean) => {
  isSelectPolicy.value = val;
};
const handleIsRuleConfiguration = (val: boolean) => {
  isRuleConfiguration.value = val;
};
// 广告
const handleAddAbs = () => {
  showAd.value = true;
  drawerAbs.value = true;
};
const handleDrawerAbs = (val: boolean) => {
  drawerAbs.value = val;
  // getList();
};
// 获取策略组需要传递的字节链接linkId和linkUrl格式
const getStrategyUrls = (val) => {
  strategyUrlList.value = val;
};
// 素材包
const handleAddMaterial = () => {
  drawerMaterial.value = true;
};

const handleDrawerMaterial = (val: boolean) => {
  drawerMaterial.value = val;
  // getList();
};
// 标题包
const handleAddHeaderPack = () => {
  drawerHeaderPack.value = true;
};
const handleDrawerHeaderPack = (val: boolean) => {
  drawerHeaderPack.value = val;
  // getList();
};
// 落地页
const handleDrawerLandingPagePack = () => {
  drawerLandingPage.value = true;
};
const handleDrawerLandingPage = (val: boolean) => {
  drawerLandingPage.value = val;
  // getList();
};
// 广告
const getPromotion = (val) => {
  promotion.value = val;
  urls.value = val.urls;
  if (urlsTemp.value && urlsTemp.value.length > 0) {
    if (addProjectInfo.value.project.microPromotionType === 'BYTE_APP' && advertiserArray.value.length == 1) {
      urls.value.map((item) => {
        item.appId = urlsTemp?.value[0]?.appId;
      });
      advertiserArray.value.map((item) => {
        item.appId = urlsTemp?.value[0]?.appId;
      });
    }
  }
  addProjectInfo.value.promotion = promotion.value;
  // addProjectInfo.value.miniProgramInfo = val.promotionMaterials?.miniProgramInfo;
  // if (addProjectInfo.value.project.microPromotionType === 'BYTE_APP' && val.linkSource == '2') {
  //   urls.value = [
  //     {
  //       url: null,
  //       advertiserId: advertiserArray.value[0].id,
  //       appId: val.promotionMaterials?.miniProgramInfo?.appId,
  //       startPath: val.promotionMaterials?.miniProgramInfo?.startPath,
  //       params: val.promotionMaterials?.miniProgramInfo?.params
  //     }
  //   ];
  // }
  // console.log('urls', urls.value);
};
const getAnchorMaterialList = (val) => {
  addProjectInfo.value.anchorMaterialList = val;
};
const getUrls = (val) => {
  console.log(val, 'getUrls');
  if (addProjectInfo.value.project.microPromotionType === 'BYTE_APP' && val.linkSource != '2') {
    urls.value = val;
  }
};
// 素材包
const getMaterialSelectedRows = (val) => {
  addProjectInfo.value.groupQos = val;
  console.log(val, 'groupQos');
};
const delAllMaterialList = () => {
  addProjectInfo.value.groupQos = [];
};
// 标题包
const getHeaderPackSelectedRows = (val) => {
  console.log('val===============>', val);
  addProjectInfo.value.titleWrap = val.data;
  addProjectInfo.value.titleWay = val.titleWay;
};
// 落地页
const getLandingPageSelectedRows = (val) => {
  addProjectInfo.value.externalUrlMaterialList = val.rows;
  addProjectInfo.value.siteWay = val.siteWay;
  console.log(addProjectInfo.value.externalUrlMaterialList, 'externalUrlMaterialList');
};
const handleIsUnifiedHand = (val: boolean) => {
  console.log(val, 'handleIsUnifiedHand');
  isUnifiedHand.value = val;
};
const handleIslandingMethods = (val: boolean) => {
  console.log(val, 'handleIslandingMethods');
  islandingMethods.value = val;
};
const handleClose = () => {
  drawerAbs.value = false;
  drawerMaterial.value = false;
  drawerHeaderPack.value = false;
};
// 保存策略组
const handleSave = debounce(async () => {
  policyGroupRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let newPromotion = JSON.parse(JSON.stringify(promotion.value));
      newPromotion.urls = strategyUrlList.value;
      let params = {
        accountId: appStore.accountId,
        name: policyGroup.policyGroupName,
        remark: policyGroupRemark.value,
        projectJson: {
          ...addProjectInfo.value,
          promotion: newPromotion,
          urls: strategyUrlList.value, //没有特别处理的urls
          // materialList: materialList.value,
          // headerPackList: headerPackList.value,
          // drawerLandingPageList: drawerLandingPageList.value,
          materialType: myMaterialType.value,
          titleWay: addProjectInfo.value.titleWay,
          siteWay: addProjectInfo.value.siteWay,
          selectAccounts: selectAccounts.value // 确保创意素材里面的分账户回显传值
        }
      };
      params.projectJson = JSON.stringify(params.projectJson);
      proxy?.$modal.loading('');
      subLoading.value = true;
      try {
        await getProjectPromotionTemplate(params);
        proxy?.$modal.msgSuccess('操作成功');
        isPolicyGroup.value = false;
        setTimeout(() => {
          router.push({ name: 'project' });
        }, 1200);
      } finally {
        subLoading.value = false;
        proxy?.$modal.closeLoading();
      }
    }
  });
}, 300);
// 提交
const handleCreate = debounce(async () => {
  //检测数据
  if (!addProjectInfo.value.project) {
    proxy?.$modal.msgError('请创建项目信息');
    return;
  }
  if (!addProjectInfo.value.promotion) {
    proxy?.$modal.msgError('请创建广告信息');
    return;
  }
  if (!addProjectInfo.value.groupQos.length) {
    proxy?.$modal.msgError('创意素材不能为空');
    return;
  }
  if (!addProjectInfo.value.titleWrap.length) {
    proxy?.$modal.msgError('标题包不能为空');
    return;
  }
  if (!addProjectInfo.value.externalUrlMaterialList.length) {
    proxy?.$modal.msgError('落地页不能为空');
    return;
  }

  let isOk = true;
  if (addProjectInfo.value.project.microPromotionType !== 'AWEME') {
    addProjectInfo.value.microAppInstanceList.map((item) => {
      if (!isOk) return;
      if (!item.microAppInstanceId) {
        isOk = false;
      }
    });
    if (!isOk) {
      proxy?.$modal.msgError('请选择小程序');
      return;
    }
  }

  let params = {
    ...addProjectInfo.value,
    promotion: promotion.value || addProjectInfo.value.promotion,
    urls: urls.value || addProjectInfo.value.urls,
    // materialList: materialList.value,
    // headerPackList: headerPackList.value,
    // drawerLandingPageList: drawerLandingPageList.value,
    materialType: myMaterialType.value,
    titleWay: addProjectInfo.value.titleWay,
    siteWay: addProjectInfo.value.siteWay
  };
  proxy?.$modal.loading('');
  subLoading.value = true;
  try {
    await createProjectPromotion(params);
    proxy?.$modal.msgSuccess('操作成功');
    setTimeout(() => {
      router.push({ name: 'project' });
    }, 1200);
  } finally {
    subLoading.value = false;
    proxy?.$modal.closeLoading();
  }
}, 300);

//打开项目列表弹窗
const openProjectList = () => {
  isShowProjectList.value = true;
};

// 生成预览
const handlePreview = debounce(async () => {
  console.log(addProjectInfo.value, 'addProjectInfo.value');
  // if (!addProjectInfo.value.microAppInstanceList) {
  //   proxy?.$modal.msgError('请到项目里去选择投放载体！');
  //   proxy?.$modal.closeLoading();
  //   showAdvPreview.value = false;
  //   return;
  // }
  // 全屏加载样式
  proxy?.$modal.loading('正在生成预览，请稍后...');
  if (showAdvPreview.value) {
    ElMessageBox.confirm('将覆盖已有预览广告, 是否继续?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        showAdvPreview.value = false;
        nextTick(async () => {
          await getCreateProjectPromotionPreview();
          showAdvPreview.value = true;
        });
      })
      .catch(() => {
        proxy?.$modal.closeLoading();
      });
  } else {
    await getCreateProjectPromotionPreview();
  }
  showAdvPreview.value = true;
}, 300);
// 获取预览
const getCreateProjectPromotionPreview = async () => {
  let params = {
    ...addProjectInfo.value,
    promotion: promotion.value || addProjectInfo.value.promotion,
    urls: urls.value || addProjectInfo.value.urls,
    // materialList: materialList.value,
    // headerPackList: headerPackList.value,
    // drawerLandingPageList: drawerLandingPageList.value,
    materialType: myMaterialType.value,
    titleWay: addProjectInfo.value.titleWay,
    siteWay: addProjectInfo.value.siteWay,
    microAppInstanceList: addProjectInfo.value.microAppInstanceList
  };
  await createProjectPromotionPreview(params)
    .then((res) => {
      if (res.code == 200) {
        tableData.value = res.data;
        paramsData.value = params;
        proxy?.$modal.closeLoading();
      } else {
        proxy?.$modal.msgError(res.msg);
        proxy?.$modal.closeLoading();
      }
    })
    .catch((err) => {
      proxy?.$modal.closeLoading();
      showAdvPreview.value = false;
    });
};
// 初始化页面数据
const init = () => {};
onMounted(() => {
  nextTick(() => {
    init();
  });
});
</script>

<style lang="scss" scoped>
::v-deep(.projectCont) {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.content {
  .items {
    border-right: 0px;
  }

  .material-list {
    padding: 0 20px;
    box-sizing: border-box;

    .material-item {
      overflow-y: scroll;
      flex-wrap: nowrap;
    }

    img {
      width: 50px;
      height: 80px;
      margin: 0 5px;
    }
  }

  .header-pack,
  .landing-page {
    .header-pack-box,
    .landing-page-box {
      .header-pack-name,
      .landing-page-name {
        width: 100%;
        height: 30px;
        line-height: 30px;
        background-color: #f5f5f5;
        padding: 0 5px;
        box-sizing: border-box;
        border-radius: 10px;
      }
    }
  }
}

.titbox {
  border-bottom: 1px solid #f1f1f1;
}
</style>
